package edu.gduf.shiro;

import edu.gduf.domain.User;
import edu.gduf.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.Set;


/**
 * 负责认证（登陆）和授权的Realm父类
 */
public class authRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService; // 注入User业务层实现类

    /**
     * 用户统一登陆认证
     * @param authToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authToken) throws AuthenticationException {
        // 用户账号和密码
        UsernamePasswordToken token = (UsernamePasswordToken) authToken;
        // 获取用户在浏览器中输入的账号
        String username = token.getUsername();
        System.out.println(token.getPassword());
        User user = userService.findUserByUserName(username);
        if(user == null)
            // 判断账号密码是否正确
            throw  new UnknownAccountException("账号错误");
        else if(user.getIs_lock() == 1)
            // 如果账号被锁定
            throw new LockedAccountException("账号被锁定");
        else
            // 登陆成功,返回成功登陆的信息
            return new SimpleAuthenticationInfo(username,user.getPassword(),null,getName());
    }


    /**
     * 用户授权的回调方法
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        // 从Shiro中获取用户名
        Object username = principalCollection.getPrimaryPrincipal();
        // 创建一个SimpleAuthorizationInfo类的对象，利用这个对象需要设置当前用户的权限信息
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        // 创建角色信息的集合
        Set<String> roles = new HashSet<String>();
        // 从数据库中获取用户所对应的所有角色信息并初始化到roles中
        User user = userService.findUserByUserName(username.toString());
        if (user.getType() == 1) {
            roles.add("user");
        } else if (user.getType() == 2) {
            roles.add("association");
        }
        // 设置角色信息
        simpleAuthorizationInfo.setRoles(roles);
        Set<String> perimission  = new HashSet<String>();
        if(user.getType() == 1)
            perimission.add("user");
        else if(user.getType() == 2)
            perimission.add("association");
        return simpleAuthorizationInfo;
    }

    /**
     * 加密规则
     * @return
     */
    @Override
    public CredentialsMatcher getCredentialsMatcher(){
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        // 设置加密方式
        hashedCredentialsMatcher.setHashAlgorithmName(Md5Hash.ALGORITHM_NAME);
        // 设置散列次数
        hashedCredentialsMatcher.setHashIterations(1);
        return hashedCredentialsMatcher;
    }


}
